﻿using System;
using System.Net;
using System.Linq;

namespace ProxyFinder.Strategies {
    public class SavedCredentialStrategy: BaseCredentialStrategy {
        
        readonly ICredentialProvider _credentialProvider;

        public SavedCredentialStrategy(ICredentialProvider credentialProvider) {
            if (credentialProvider == null) {
                throw new ArgumentNullException("credentialProvider");
            }
            _credentialProvider = credentialProvider;
        }

        public override IWebProxy GetProxy(Uri uri) {
            WebProxy systemProxy = GetSystemProxy(uri);
            // Try and see if we have credentials saved for the system proxy first so that we can
            // validate and see if we should use them.
            if(HasCredentials(systemProxy.Address)) {
                WebProxy proxy = GetSystemProxy(uri);
                proxy.Credentials = _credentialProvider.GetCredentials(systemProxy.Address.Host).FirstOrDefault();
                return proxy;
            }
            return null;
        }

        /// <summary>
        /// Helper method to return true or false if credentials were discovered for the given Uri.
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        private bool HasCredentials(Uri uri) {
            return _credentialProvider.GetCredentials(uri.Host).Count() > 0;
        }

    }
}
